<template>
  <div class="login-page">
    <div class="login-header">
      <img class="logo" src="@/assets/images/logo.svg" alt="logo" />
      <div class="title"><span>XYZ</span></div>
    </div>
    <div class="login-form">
      <el-form ref="formRef" :model="loginForm" :rules="rules">
        <el-form-item prop="userName">
          <el-input v-model="loginForm.userName" :placeholder="$t('login.tipText')" />
        </el-form-item>
        <el-form-item prop="password">
          <el-input v-model="loginForm.password" type="password" :placeholder="$t('login.tipText2')" />
        </el-form-item>
        <el-form-item>
          <el-button class="login-btn" type="primary" color="var(--color-primary)" :loading="loading" @click="onSubmit">
            {{ $t("login.title") }}
          </el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive } from "vue"
import { useRouter } from "vue-router"
import { useI18n } from "vue-i18n"
import { TOKEN } from "@/constants"
import { userLogin } from "@/api/auth"
import { showErrorToast } from "@/utils/toast"
import type { FormInstance, FormRules } from "element-plus"

const formRef = ref<FormInstance | null>(null)
const router = useRouter()
const { t } = useI18n()

const loading = ref(false)

// 登录表单
const loginForm = reactive<AuthLoginRequest>({
  userName: "",
  password: ""
})

const rules = reactive<FormRules<AuthLoginRequest>>({
  userName: [{ required: true, message: t("login.tipText"), trigger: "blur" }],
  password: [{ required: true, message: t("login.tipText2"), trigger: "blur" }]
})

/**
 * 登录
 */
const onSubmit = () => {
  formRef.value?.validate(async (valid) => {
    if (valid) {
      try {
        loading.value = true
        const res = await userLogin(loginForm)
        if (res.data) {
          // 保存 Token
          localStorage.setItem(TOKEN, res.data.token ?? "")
          // 去到首页
          router.replace("/")
        }
      } catch (error: any) {
        showErrorToast(error.message)
      } finally {
        loading.value = false
      }
    }
  })
}
</script>

<style lang="scss" scoped>
.login-page {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 100vh;
  padding-bottom: 100px;
}

.login-header {
  display: flex;
  align-items: center;
  margin-bottom: 20px;

  img {
    width: 40px;
    height: 40px;
  }

  .title {
    margin-left: 8px;
    font-size: 20px;
    font-family: bold;
  }
}

.login-form {
  width: 300px;

  .login-btn {
    width: 100%;
  }
}
</style>
